﻿using Microsoft.Office.Interop.Word;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using MSWord = Microsoft.Office.Interop.Word;
using MSWordApplication = Microsoft.Office.Interop.Word.Application;

namespace WPS_Assistant
{
    public partial class FormMain : Form
    {
        /* 常量区 */
        public const int CONDITION_CLASS_NUM_MAX = 7;//最大支持的条件类别数量
        public const int CONDITION_NUM_MAX = 15;

        private String pictureDirPath = null;//数据图片
        private String outputDirPath = null;//输出文件夹
        private MSWord.Document doc = null;//输出的文档
        private String docName = "output";//默认输出文件名
        private int conditionClassNum = 1;//条件类别默认数量
        private String[] conditonClassName = new String[CONDITION_CLASS_NUM_MAX];//每个条件类别名称
        private int[] conditionNum = new int[CONDITION_CLASS_NUM_MAX];//每个条件类别的条件数量
        private String[] conditionUnit = new String[CONDITION_CLASS_NUM_MAX];//每个条件类别的单位

        MSWord.Range range = null;//当前编辑范围
        MSWord.Paragraph paragraph = null;//当前段落
        MSWord.Table table = null;//数据表格
        public FormMain()
        {
            InitializeComponent();

            /* 初始化 */

            /* 每个条件类别的名称初始化为0 */
            Array.Clear(conditonClassName, 0, CONDITION_CLASS_NUM_MAX);
            /* 每个条件类别的条件数量初始化为0 */
            Array.Clear(conditionNum, 0, CONDITION_CLASS_NUM_MAX);
            /* 每个条件类别的单位初始化为0 */
            Array.Clear(conditionUnit, 0, CONDITION_CLASS_NUM_MAX);

            /* 图片后缀名默认选择第一个：.png */
            this.comboBox_PictureSuffix.SelectedIndex = 0;
            /* 分隔符默认选择第一个：Tab */
            this.comboBox_SplitSymbol.SelectedIndex = 0;

            showInit();
        }

        /***************************************/
        /*      控件信号槽                     */
        /***************************************/
        /** 
         * @brief   设置图片数据文件夹地址 
         */
        private void button_SlectPictureDirPath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog_OpenFolder.ShowDialog() == DialogResult.OK)
            {
                pictureDirPath = folderBrowserDialog_OpenFolder.SelectedPath;
                this.textBox_PictureDirPath.Text = pictureDirPath;
            }
        }

        /** 
         * @brief   设置输出文档文件夹地址 
         */
        private void button_OutputDirPath_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog_OpenFolder.ShowDialog() == DialogResult.OK)
            {
                outputDirPath = folderBrowserDialog_OpenFolder.SelectedPath;
                this.textBox_OutputDirPath.Text = outputDirPath;
            }
        }

        /** 
         * @brief   输出按钮 
         */
        private void button_Output_Click(object sender, EventArgs e)
        {
            MSWordApplication wordApp = new MSWordApplication();
            doc = wordApp.Documents.Add();

            // 获取页面设置对象
            PageSetup pageSetup = doc.PageSetup;
            // 设置页边距，单位为磅
            pageSetup.TopMargin = wordApp.CentimetersToPoints(1f);    // 上边距 1 厘米
            pageSetup.BottomMargin = wordApp.CentimetersToPoints(1f); // 下边距 1 厘米
            pageSetup.LeftMargin = wordApp.CentimetersToPoints(1f);   // 左边距 1 厘米
            pageSetup.RightMargin = wordApp.CentimetersToPoints(1f);  // 右边距 1 厘米

            int sum = calculateConditionSum();//计算总行数

            insertTable(sum, 2);//插入表格

            insertPitch(sum, wordApp);//插入图片

            insertComment(sum, wordApp);//插入注释

            // 保存文档
            object fileName = outputDirPath + "\\" + docName;
            doc.SaveAs2(ref fileName);

            // 关闭文档
            doc.Close(false);

            // 退出 Word 应用程序
            wordApp.Quit();

            MessageBox.Show("Finish");
            String Path = @outputDirPath + "\\" + docName+ ".docx";
            System.Diagnostics.Process.Start(Path);//打开文档
            Console.WriteLine("Document created and saved successfully.");
        }

        /** 
         * @brief   条件类别增加按钮 
         */
        private void button_conditionClassAdd_Click(object sender, EventArgs e)
        {
            if (conditionClassNum < CONDITION_CLASS_NUM_MAX)
            {
                conditionClassNum++;
            }
            if (conditionClassNum > 1)
            {
                this.button_conditionClassSub.Visible = true;
                this.button_conditionClassSub.Enabled = Enabled;
            }
            showGroupBox_conditionClassX(conditionClassNum);
        }

        /** 
         * @brief   条件类别减少按钮 
         */
        private void button_conditionClassSub_Click(object sender, EventArgs e)
        {
            if (conditionClassNum > 1)
            {
                conditionClassNum--;
            }
            if (conditionClassNum == 1)
            {
                this.button_conditionClassSub.Visible = false;
                this.button_conditionClassSub.Enabled = false;
            }
            showGroupBox_conditionClassX(conditionClassNum);
        }

        private void textBox_conditionNum1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum1.Text);
                    conditionNum[0] = num;
                    updateShowAllTextBox_conditions();
                }
                catch
                {
                    this.textBox_conditionNum1.Text = "0";
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum1.Text);
                    conditionNum[0] = num;
                    updateShowAllTextBox_conditions();
                }
            }
        }
        private void textBox_conditionNum2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum2.Text);
                    conditionNum[1] = num;
                    updateShowAllTextBox_conditions();
                }
                catch
                {
                    this.textBox_conditionNum2.Text = "0";
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum2.Text);
                    conditionNum[1] = num;
                    updateShowAllTextBox_conditions();
                }
            }
        }

        private void textBox_conditionNum3_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum3.Text);
                    conditionNum[2] = num;
                    updateShowAllTextBox_conditions();
                }
                catch
                {
                    this.textBox_conditionNum3.Text = "0";
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum3.Text);
                    conditionNum[2] = num;
                    updateShowAllTextBox_conditions();
                }
            }
        }

        private void textBox_conditionNum4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum4.Text);
                    conditionNum[3] = num;
                    updateShowAllTextBox_conditions();
                }
                catch
                {
                    this.textBox_conditionNum4.Text = "0";
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum4.Text);
                    conditionNum[3] = num;
                    updateShowAllTextBox_conditions();
                }
            }
        }

        private void textBox_conditionNum5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum5.Text);
                    conditionNum[4] = num;
                    updateShowAllTextBox_conditions();
                }
                catch
                {
                    this.textBox_conditionNum5.Text = "0";
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum5.Text);
                    conditionNum[4] = num;
                    updateShowAllTextBox_conditions();
                }
            }
        }

        private void textBox_conditionNum6_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum6.Text);
                    conditionNum[5] = num;
                    updateShowAllTextBox_conditions();
                }
                catch
                {
                    this.textBox_conditionNum6.Text = "0";
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum6.Text);
                    conditionNum[5] = num;
                    updateShowAllTextBox_conditions();
                }
            }
        }

        private void textBox_conditionNum7_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    int num = 0;
                    num = int.Parse(this.textBox_conditionNum7.Text);
                    conditionNum[6] = num;
                    updateShowAllTextBox_conditions();
                }
                catch {
                        this.textBox_conditionNum7.Text = "0";
                        int num = 0;
                        num = int.Parse(this.textBox_conditionNum7.Text);
                        conditionNum[6] = num;
                        updateShowAllTextBox_conditions();
                }                               
            }
        }
        /***************************************/
        /*      UI操作方法                     */
        /***************************************/
        /**
         * @brief   UI初始化
         */
        public void showInit()
        {
            showGroupBox_conditionClassX(conditionClassNum);
            updateShowAllTextBox_conditions();
        }
        /**
         * @brief   增加条件类别的时候增加显示GroupBox_conditionClass
         */
        public void showGroupBox_conditionClassX(int num)
        {
            int Num = num;
            if (Num > CONDITION_CLASS_NUM_MAX) Num = CONDITION_CLASS_NUM_MAX;
            switch (Num)
            {
                case 1:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = false;
                    clearCondition(2);
                    this.groupBox_conditionClass3.Visible = false;
                    clearCondition(3);
                    this.groupBox_conditionClass4.Visible = false;
                    clearCondition(4);
                    this.groupBox_conditionClass5.Visible = false;
                    clearCondition(5);
                    this.groupBox_conditionClass6.Visible = false;
                    clearCondition(6);
                    this.groupBox_conditionClass7.Visible = false;
                    clearCondition(7);
                    break;
                case 2:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = true;
                    this.groupBox_conditionClass3.Visible = false;
                    clearCondition(3);
                    this.groupBox_conditionClass4.Visible = false;
                    clearCondition(4);
                    this.groupBox_conditionClass5.Visible = false;
                    clearCondition(5);
                    this.groupBox_conditionClass6.Visible = false;
                    clearCondition(6);
                    this.groupBox_conditionClass7.Visible = false;
                    clearCondition(7);
                    break;
                case 3:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = true;
                    this.groupBox_conditionClass3.Visible = true;
                    this.groupBox_conditionClass4.Visible = false;
                    clearCondition(4);
                    this.groupBox_conditionClass5.Visible = false;
                    clearCondition(5);
                    this.groupBox_conditionClass6.Visible = false;
                    clearCondition(6);
                    this.groupBox_conditionClass7.Visible = false;
                    clearCondition(7);
                    break;
                case 4:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = true;
                    this.groupBox_conditionClass3.Visible = true;
                    this.groupBox_conditionClass4.Visible = true;
                    this.groupBox_conditionClass5.Visible = false;
                    clearCondition(5);
                    this.groupBox_conditionClass6.Visible = false;
                    clearCondition(6);
                    this.groupBox_conditionClass7.Visible = false;
                    clearCondition(7);
                    break;
                case 5:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = true;
                    this.groupBox_conditionClass3.Visible = true;
                    this.groupBox_conditionClass4.Visible = true;
                    this.groupBox_conditionClass5.Visible = true;
                    this.groupBox_conditionClass6.Visible = false;
                    clearCondition(6);
                    this.groupBox_conditionClass7.Visible = false;
                    clearCondition(7);
                    break;
                case 6:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = true;
                    this.groupBox_conditionClass3.Visible = true;
                    this.groupBox_conditionClass4.Visible = true;
                    this.groupBox_conditionClass5.Visible = true;
                    this.groupBox_conditionClass6.Visible = true;
                    this.groupBox_conditionClass7.Visible = false;
                    this.groupBox_conditionClass7.Visible = false;
                    clearCondition(7);
                    break;
                case 7:
                    this.groupBox_conditionClass1.Visible = true;
                    this.groupBox_conditionClass2.Visible = true;
                    this.groupBox_conditionClass3.Visible = true;
                    this.groupBox_conditionClass4.Visible = true;
                    this.groupBox_conditionClass5.Visible = true;
                    this.groupBox_conditionClass6.Visible = true;
                    this.groupBox_conditionClass7.Visible = true;
                    break;
                default: break;
            };
            updateShowAllTextBox_conditions();
        }

        /**
         * @brief   增加条件数量的时候增加显示TextBox_condition
         * @param   group   条件类别组
         * @param   num     对应条件类别组的的条件个数
         */
        void showTextBox_conditionX(int group, int num)
        {
            int Group = group;
            int Num = num;
            int i = 0;
            for (i = 0; i < num; i++)
            {
                TextBox textbox = this.Controls.Find("textBox_condition" + ""+group + "_" +""+ (i + 1), true).FirstOrDefault() as TextBox;
                if(textbox != null)
                    textbox.Visible = true;
            }
            for (; i < CONDITION_NUM_MAX; i++)
            {
                TextBox textbox = this.Controls.Find("textBox_condition" + "" + group + "_" + "" + (i + 1), true).FirstOrDefault() as TextBox;
                if (textbox != null)
                    textbox.Visible = false;
            }
        }

        /**
         * @brief   更新所有显示TextBox_condition
         */
        void updateShowAllTextBox_conditions()
        {
            showTextBox_conditionX(1, conditionNum[0]);
            showTextBox_conditionX(2, conditionNum[1]);
            showTextBox_conditionX(3, conditionNum[2]);
            showTextBox_conditionX(4, conditionNum[3]);
            showTextBox_conditionX(5, conditionNum[4]);
            showTextBox_conditionX(6, conditionNum[5]);
            showTextBox_conditionX(7, conditionNum[6]);
        }

        /**
         * @brief   清除类别对应的所有条件
         */
        void clearCondition(int Class)
        {
            TextBox textbox0 = this.Controls.Find("textBox_conditionNum" + Class, true).FirstOrDefault() as TextBox;
            textbox0.Text = "0";
            conditionNum[Class - 1] = 0;
            for (int i = 1; i <= CONDITION_NUM_MAX; i++)
            {
                TextBox textbox = this.Controls.Find("textBox_condition" + Class + "_" + i, true).FirstOrDefault() as TextBox;
                textbox.Text = null;
            }

            TextBox textbox1 = this.Controls.Find("textBox_conditionUnit" + Class, true).FirstOrDefault() as TextBox;
            textbox1.Text = null;
            TextBox textbox2 = this.Controls.Find("textBox_conditionClassName" + Class, true).FirstOrDefault() as TextBox;
            textbox2.Text = null;
        }

        /***************************************/
        /*      文档操作的方法                 */
        /***************************************/
        /**
         * @brief   插入新段落
         */
        public void insertNewPargraph()
        {
            /* 更新文档的内容范围 */
            range = doc.Content;

            /* 编辑位置移动到末尾 */
            range.Collapse(MSWord.WdCollapseDirection.wdCollapseEnd);

            /* 在当前范围后插入一个新段落 */
            paragraph = doc.Paragraphs.Add(range);

            /* 在新段落后更新范围 */
            range = paragraph.Range;
            paragraph.Range.InsertParagraphAfter();
        }


        /**
         * @brief   插入表格
         */
        public void insertTable(int rows, int columns)
        {
            /* 更新文档的内容范围 */
            range = doc.Content;

            /* 编辑位置移动到末尾 */
            range.Collapse(MSWord.WdCollapseDirection.wdCollapseEnd);

            /* 插入表格 */
            table = doc.Tables.Add(range, rows, columns);

            /* 表格线框显示实线 */
            table.Borders.Enable = 1;

            /* 自动调整列宽 */
            table.AllowAutoFit = true;
        }

        /**
         * @brief   读取图片并插入
         */
        public void insertPitch(int sum, MSWordApplication wordApp)
        {
            string[] imageFiles = Directory.GetFiles(pictureDirPath, "*" + this.comboBox_PictureSuffix.Text);
            int row = 0;
            int colu = 2;
            for (int i = 0; i < sum; i++)
            {
                if (colu == 2)
                {
                    colu = 1;
                    row++;
                }
                else if (colu == 1)
                {
                    colu = 2;
                }
                Range cellRange = table.Cell(row, colu).Range;
                try
                {
                    InlineShape picture = cellRange.InlineShapes.AddPicture(imageFiles[i]);
                    picture.LockAspectRatio = Microsoft.Office.Core.MsoTriState.msoTrue; // 锁定纵横比
                    picture.Width = wordApp.CentimetersToPoints(9f);    // 图片高度 6厘米
                    if (colu == 2)
                        row += 1;
                }
                catch
                {
                    break;
                }
            }
        }

        /**
         * @brief   插入注释
         */
        public void insertComment(int sum, MSWordApplication wordApp)
        {
            int row = 1;
            int colu = 2;
            int a = 1, b = 1, c = 1, d = 1, e = 1, f = 1, g = 1;
            for (int i = 0; i < sum; i++)
            {
                if (colu == 2)
                {
                    colu = 1;
                    row++;
                }
                else if (colu == 1)
                {
                    colu = 2;
                }
                Range cellRange = table.Cell(row, colu).Range;
                try
                {
                    String CommentPrefix = this.textBox_CommentPrefix.Text;
                    String CommentSuffix = this.textBox_CommentSuffix.Text;
          
                    String SplitSymbol = null;
                    if (this.comboBox_SplitSymbol.Text.Equals("Tab"))
                    {
                        SplitSymbol = "\t";
                    }
                    else if (this.comboBox_SplitSymbol.Text.Equals("空格"))
                    {
                        SplitSymbol = " ";
                    }
                    else SplitSymbol = this.comboBox_SplitSymbol.Text;
                    String Comment = null;
                    if (conditionClassNum >= 1)
                        Comment +=  backStringClassName("a") + ": " + backStringConditionName("a", a) + backStringConditionUnitName("a");
                    if (conditionClassNum >= 2)
                        Comment += SplitSymbol + backStringClassName("b") + ": " + backStringConditionName("b", b) + backStringConditionUnitName("b");
                    if (conditionClassNum >= 3)
                        Comment += SplitSymbol + backStringClassName("c") + ": " + backStringConditionName("c", c) + backStringConditionUnitName("c");
                    if (conditionClassNum >= 4)
                        Comment += SplitSymbol + backStringClassName("d") + ": " + backStringConditionName("d", d) + backStringConditionUnitName("d");
                    if (conditionClassNum >= 5)
                        Comment += SplitSymbol + backStringClassName("e") + ": " + backStringConditionName("e", e) + backStringConditionUnitName("e");
                    if (conditionClassNum >= 6)
                        Comment += SplitSymbol + backStringClassName("f") + ": " + backStringConditionName("f", f) + backStringConditionUnitName("f");
                    if (conditionClassNum >= 6)
                        Comment += SplitSymbol + backStringClassName("g") + ": " + backStringConditionName("g", g) + backStringConditionUnitName("g");
                    int index = i + 1;
                    cellRange.Text = "Graph"+ index + " "+CommentPrefix +" "+Comment;
                    cellRange.Font.Name = "Times New Roman";
                    // 设置字号
                    cellRange.Font.Size = 10;
                    // 设置加粗
                    cellRange.Font.Bold = 0; // 1 为加粗，0 为不加粗
                                             // 设置斜体
                    cellRange.Font.Italic = 0; // 1 为斜体，0 为不斜体
                                               // 设置下划线
                    //cellRange.Font.Underline = WdUnderline.wdUnderlineSingle;
                    // 设置文字颜色
                    cellRange.Font.Color = WdColor.wdColorBlack; // 文字颜色为红色

                    // 设置对齐方式
                    cellRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    //***//

                    g++;
                    if (g > conditionNum[6])
                    {
                        g = 1;
                        f++;
                    }
                    if (f > conditionNum[5])
                    {
                        f = 1;
                        e++;
                    }
                    if (e > conditionNum[4])
                    {
                        e = 1;
                        d++;
                    }
                    if (d > conditionNum[3])
                    {
                        d = 1;
                        c++;
                    }
                    if (c > conditionNum[2])
                    {
                        c = 1;
                        b++;
                    }
                    if (b > conditionNum[1])
                    {
                        b = 1;
                        a++;
                    }
                    if (a > conditionNum[0])
                    {
                        a = 1;
                    }

                    if (colu == 2)
                        row += 1;
                }
                catch
                {
                    break;
                }
            }
        }

        /***************************************/
        /*      数据计算的方法                 */
        /***************************************/
        /**
         * @brief   计算条件组合总数
         */
        public int calculateConditionSum()
        {
            int sum = 1;
            for (int i = 0; i < CONDITION_CLASS_NUM_MAX; i++)
            {
                //textBox_conditionNum1
                TextBox textbox = this.Controls.Find("textBox_conditionNum" + "" + (i+1), true).FirstOrDefault() as TextBox;
                if (textbox != null)
                {
                    if (!textbox.Text.Equals("0"))
                    {
                        sum *= int.Parse(textbox.Text);
                    }
                }
            }
            if (sum == 1)
                return 0;
            else {
                if (sum % 2 == 1)
                    sum += 1;
                return sum;
            }
        }
        /**
         * 
         */
        public String backStringConditionName(String Class,int num)
        {
            String ret = null;
            int clas = 0;
            switch (Class)
            {
                case "a":
                    clas = 1;
                    break;
                case "b": clas = 2; break;
                case "c": clas = 3; break;
                case "d": clas = 4; break;
                case "e": clas = 5; break;
                case "f": clas = 6; break;
                case "g": clas = 7; break;
                default: break;
            }
            //textBox_condition3_4
            TextBox textbox = this.Controls.Find("textBox_condition" + clas+"_"+num, true).FirstOrDefault() as TextBox;
            ret = textbox.Text;
            return ret;
        }

        public String backStringConditionUnitName(String Class)
        {
            String ret = null;
            int clas = 0;
            switch (Class)
            {
                case "a":
                    clas = 1;
                    break;
                case "b": clas = 2; break;
                case "c": clas = 3; break;
                case "d": clas = 4; break;
                case "e": clas = 5; break;
                case "f": clas = 6; break;
                case "g": clas = 7; break;
                default: break;
            }
            //textBox_conditionUnit1
            TextBox textbox = this.Controls.Find("textBox_conditionUnit" + clas, true).FirstOrDefault() as TextBox;
            //if (!textbox.Text.Equals(""))
            //    ret = "\t\t" + textbox.Text;
            return ret;
        }
        public String backStringClassName(String Class)
        {
            String ret = null;
            int clas = 0;
            switch (Class)
            {
                case "a":
                    clas = 1;
                    break;
                case "b": clas = 2; break;
                case "c": clas = 3; break;
                case "d": clas = 4; break;
                case "e": clas = 5; break;
                case "f": clas = 6; break;
                case "g": clas = 7; break;
                default: break;
            }
            //textBox_conditionClassName1
            TextBox textbox = this.Controls.Find("textBox_conditionClassName" + clas, true).FirstOrDefault() as TextBox;
            ret = textbox.Text;
            return ret;
        }
    }

}
